package com.snicesoft.jfinal.vue;

import com.jfinal.config.*;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.snicesoft.jfinal.vue.handler.ProxyHandler;
import com.snicesoft.jfinal.vue.source.HttpOrFileSourceFactory;

public class AppConfig extends JFinalConfig {

    static Prop p;

    public static boolean isDevMode = false;

    /**
     * 启动入口，运行此 main 方法可以启动项目，此 main 方法可以放置在任意的 Class 类定义中，不一定要放于此
     */
    public static void main(String[] args) {
        UndertowServer.start(AppConfig.class);
    }

    /**
     * PropKit.useFirstFound(...) 使用参数中从左到右最先被找到的配置文件
     * 从左到右依次去找配置，找到则立即加载并立即返回，后续配置将被忽略
     */
    static void loadConfig() {
        if (p == null) {
            p = PropKit.useFirstFound("app-config-dev.txt", "app-config.txt");
            isDevMode = p.getBoolean("devMode", false);
        }
    }

    @Override
    public void configConstant(Constants constants) {
        loadConfig();
        constants.setDevMode(isDevMode);
    }

    @Override
    public void configRoute(Routes routes) {
        String viewPath = p.get("proxyViewPath", "/WEB-INF/");
        routes.add("/", IndexController.class, viewPath);
    }

    @Override
    public void configEngine(Engine engine) {
        engine.setDevMode(isDevMode);
        engine.setSourceFactory(new HttpOrFileSourceFactory());
    }

    @Override
    public void configPlugin(Plugins plugins) {

    }

    @Override
    public void configInterceptor(Interceptors interceptors) {

    }

    @Override
    public void configHandler(Handlers handlers) {
        String proxyUrl = p.get("proxyUrl");
        String jsProxyUrl = p.get("jsProxyUrl");
        if (!StrKit.isBlank(proxyUrl)) {
            handlers.add(new ProxyHandler(proxyUrl, jsProxyUrl));
        }
    }
}
